<template>
  <div ref="pieChart" :style="chartStyle" />
</template>

<script>
import echarts from 'echarts'

export default {
  name: 'PieChart',
  props: {
    data: {
      type: Array, // 数据格式 [{name: 'xxx', value: 'xxx'}, ...]
      required: true
    },
    title: {
      type: String,
      default: ''
    },
    subtitle: {
      type: String,
      default: ''
    },
    legend: {
      type: Boolean,
      default: true
    },
    chartStyle: {
      type: Object,
      default: () => {
        return {
          width: '100%',
          height: '100%'
        }
      }
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.pieChart
      const myChart = echarts.init(chartDom)
      const option = {
        title: {
          text: this.title,
          subtext: this.subtitle,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          show: this.legend,
          orient: 'vertical',
          left: 'left',
          data: this.data.map(item => item.name)
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: this.data.sort((a, b) => a.value - b.value),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: false
            },
            labelLine: {
              show: false
            }
          }
        ]
      }
      myChart.setOption(option)
    }
  }
}
</script>
